<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
// import HelloWorld from './components/HelloWorld.vue'
import { computed, onMounted, ref, watch } from 'vue'
import * as Icons from '@element-plus/icons-vue'
import { API_TOKEN_STORAGE_KEY } from '../api/request'
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
// import { profile } from '../api/user'

const router = useRouter()
const route = useRoute()
const store = useStore()
// const username = ref('_user_')
const width768 = computed(() => store.state.windowWidth <= 768)
const username = computed(() => store.state.username)
const menus = computed(() => store.state.menus)
const navGroups = computed(() => {
  let groupIcon = {}
  let groupNavs = {}
  for (const i in menus.value) {
    const m = menus.value[i]
    if (m.path.split('/').length > 1) continue
    if (Object.prototype.hasOwnProperty.call(groupNavs, m.group)) {
      groupNavs[m.group].push(m)
    }else{
      groupNavs[m.group] = [m]
    }
    if (m.icon && Object.keys(Icons).indexOf(m.icon) >= 0) {
      groupIcon[m.group] = m.icon
    }
  }
  
  let groups = []
  for (const group in groupNavs) {
    let g = {
      group,
      items: groupNavs[group],
    }
    if (groupIcon[group]) {
      g.icon = Icons[groupIcon[group]]
    }
    groups.push(g)
  }
  return groups
})
const breadCrumb = computed(() => {
  const pathSplit = route.path.split('/')
  const bread = []
  for (let i = pathSplit.length; i >= 0; i--) {
    const path = pathSplit.slice(2,i).join('/')
    if (path) {
      bread.unshift({
        bread: menus.value.find(m => m.path == path).name,
        path
      })
    }
    
  }
  return bread
})
const navCollapse = ref(false)

function userProfileLoaded(res) {
  console.log('userProfileLoaded', res)
}

onMounted(async() => {
  console.log('onMounted-home')
  navCollapse.value = width768.value
  watch(width768, () => {
    navCollapse.value = width768.value
  })
})

// onBeforeRouteUpdate(() => {
//   console.log('onBeforeRouteUpdate-home')
// })

function toggleCollapse() {
  navCollapse.value = !navCollapse.value
}

function onDropdownClick(e) {
  if (e == 'logout') {
    localStorage.removeItem(API_TOKEN_STORAGE_KEY)
    router.replace('/login')
  }
}

function onMenuSelect(path) {
  router.push(`/home/${path}`)
}

function onBreadCrumbClick(path) {
  router.push(`/home/${path}`)
}

</script>

<template>
  <el-container class="main">

    <el-header class="header-bar">
      <div class="title">管理后台</div>
      <div class="actions">
        <el-dropdown trigger="click" @command="onDropdownClick">
          <span>
            {{username}}
            <el-icon class="el-icon--right">
              <Icons.ArrowDown />
            </el-icon>
          </span>
          <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="logout">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
        </el-dropdown>
      </div>
    </el-header>

    <el-container class="app-body">

      <el-aside :width="navCollapse?'64px':'200px'">
        <div class="aside-bar">
          <el-scrollbar class="nav-scroll" view-style="height:100%">
            <el-menu class="nav-menu" style="height:100%" 
            background-color="#1E222D" text-color="#ffffff"
            active-text-color="#ffffff"
            :collapse="navCollapse" :unique-opened="true"
            :default-active="route.path.split('/').slice(2).join('/')"
            @select="onMenuSelect">

              <el-sub-menu v-for="group in navGroups" :key="group.group" :index="group.group">
                <template #title>
                  <el-icon>
                    <component v-if="group.icon" :is="group.icon" />
                  </el-icon>
                  <span>{{group.group}}</span>
                </template>
                <el-menu-item v-for="item in group.items" :key="item.path" :index="`${item.path}`" class="grouped-nav">
                  <template #title>{{item.name}}</template>
                </el-menu-item>
              </el-sub-menu>

            </el-menu>
          </el-scrollbar>
          <el-button size="large" color="#262F3E" style="border-radius:0" @click="toggleCollapse">
            <el-icon :size="24">
              <Icons.ArrowLeft v-if="!navCollapse" />
              <Icons.ArrowRight v-else />
            </el-icon>
          </el-button>
        </div>
        
      </el-aside>

      <el-main class="page-view">
        <el-breadcrumb class="breadcrumb">
          <el-breadcrumb-item v-for="bread in breadCrumb" :key="bread.path" :to="{path : `/home/${bread.path}`}" @click="onBreadCrumbClick(bread.path)">
            {{bread.bread}}
          </el-breadcrumb-item>
        </el-breadcrumb>
        <el-scrollbar>
          <router-view class="router-view"></router-view>
        </el-scrollbar>
      </el-main>

    </el-container>
  </el-container>
</template>

<style>
  .main {
    height: 100%;
  }
  .placement {
    flex: 1;
  }
  .header-bar {
    display: flex;
    /* border-bottom: var(--el-border-base); */
    background: #262F3E;
  }
  .header-bar * {
    color: #fff;
  }
  .header-bar .title {
    width: 180px;
    font-size: 24px;
    line-height: var(--el-header-height);
  }
  .header-bar .actions {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: flex-end;
  }
  .header-bar .actions * {
    cursor: pointer;
  }

  .app-body {
    height: calc(100% - 60px);
  }
  .aside-bar {
    display: flex;
    flex-direction: column;
    height: 100%;
    /* border-right: var(--el-border-base); */
  }
  .nav-scroll {
    flex: 1;
  }
  .nav-menu {
    height: 100%;
    border: none;
  }
  .grouped-nav {
    background: #151822;
    text-indent: 1em;
  }
  .el-menu-item:hover {
    background: #262F3E;
  }
  .el-menu-item.is-active {
    background: var(--el-color-primary);
  }
  .page-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0;
    background: #f2f2f2;
  }
  .breadcrumb {
    padding: 10px 20px;
  }
  .router-view {
    flex: 1;
    padding: 10px 20px;
  }
</style>
